<?php
/**
 * 商品类
 */
namespace app\admin\controller;

use app\admin\business\GoodsBus;
use app\admin\model\Goods as goodsModel;
use common\Tree;
use think\facade\Db;
use think\facade\Request;
use think\facade\View;

class Goods extends Common
{

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 商品列表
     * @author lijia
     * @date 2019-08-08
     */
    public function index()
    {
        if (Request::isPost()) {
            $key = input('post.key');
            $cid = input('post.cid');
            $status = input('post.status',0,'intval');
            $page = input('page') ? input('page') : 1;
            $pageSize = input('limit') ? input('limit') : config('pageSize');
            $sort_by = input('sort_by') ? input('sort_by') : 'sort';
            $sort_order = input('sort_order') ? input('sort_order') : 'asc';
            $where = [];
            if ($key) {
                $where[] = ['a.title|b.category_name', 'like', "%" . $key . "%"];
            }
            if ($cid) {
                $tree = self::getTree($cid);
                $where[] = ['a.cid', 'in', $tree];
            }
            if ($status) {
                $where[] = ['a.status', '=', $status];
            }
            $list = GoodsBus::getList($where,$sort_by,$sort_order,$pageSize,$page);
            return $result = ['code' => 0, 'msg' => '获取成功!', 'data' => $list['data'], 'count' => $list['total'], 'rel' => 1];
        }
        self::categorySelect();
        return View::fetch();
    }

    public function category()
    {
        if (request()->isPost()) {
            $cateList = Db::name('category')->order('sort','asc')->select()->toArray();
            return ['code' => 0, 'msg' => '获取成功！', 'data' => $cateList, 'rel' => 1];
        } else {
            $path = config("view.view_path") . strtolower(CONTROLLER) . "/" . strtolower(ACTION) . "." . config("view.view_suffix");
            if (file_exists($path)) {
                return View::fetch($path);
            } else {
                $path = config("view.view_path") . "public/" . strtolower(ACTION) . "." . config("view.view_suffix");
                return View::fetch($path);
            }
        }
    }

    /**
     * 添加分类
     * @return null
     */
    public function categoryAdd()
    {
        try {
            $pid = input('param.pid',0,'intval');
            if (request()->isPost()) {
                $data = input('param.');
                $data['create_time'] = time();
                Db::name('category')->insert($data);
                return ['code' => 0, 'msg' => '添加成功！'];
            } else {
                if ($pid){
                    $categorys = Db::name("category")->where('category_id',$pid)->select()->toArray();
                    $Tree = new Tree();
                    $arr = $Tree->cate($categorys);
                    $this->assign('info',['pid' => $pid]);
                    $this->assign('categorys',$arr);
                }else{
                    self::categorySelect();
                }
                return View::fetch('category_edit');
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    public function categoryEdit()
    {
        try {
            if (request()->isPost()) {
                $post= input('post.');
                $data = [
                    'category_name' => $post['category_name'],
                    'sort' => $post['sort'],
                    'update_time' => time()
                ];
                Db::name('category')->where('category_id',$post['category_id'])->update($data);
                return ['code' => 0, 'msg' => '编辑成功！'];
            } else {
                $id = input('get.id', 0, "intval");
                if (!$id) {
                    return ['code' => 2000, 'msg' => '非法请求！'];
                }
                $info = Db::name('category')->where('category_id',$id)->find();
                $this->assign('info', $info);
                self::categorySelect();
                return View::fetch('category_edit');
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    public function categoryDelete(){
        $id = input('post.id');
        $is_system = Db::name('category')->where('category_id',$id)->where('is_system',1)->find();
        if ($is_system){
            return ['code' => 3000, 'msg' => '系统分类不能删除'];
        }
        $res = Db::name('category')->where('category_id',$id)->delete();
        if ($res){
            return ['code' => 0, 'msg' => '删除成功！'];
        }else{
            return ['code' => 3000, 'msg' => '删除失败'];
        }
    }

    private function categorySelect()
    {
        $categorys = Db::name("category")->select()->toArray();
        $Tree = new Tree();
        $arr = $Tree->cate($categorys);
        $this->assign('categorys',$arr);
    }

    private function getTree($cid){
        $categorys = Db::name("category")->select()->toArray();
        $Tree = new Tree();
        $str = $Tree->getAllCid($categorys,$cid);
        return $str;
    }

    /**
     * 添加商品
     * @author lijia
     * @date 2019-08-08
     */
    public function add()
    {
        try {
            if (request()->isPost()) {
                $data = input('post.');
                unset($data['file']);
                $data['create_time'] = date('Y-m-d H:i:s',time());
                if (isset($data['images'])){
                    $data['images']= json_encode($data['images'],true);
                }else{
                    return ['code' => 3000, 'msg' => '请添加商品轮播'];
                }
                Db::name('goods')->insert($data);
                return ['code' => 0, 'msg' => '操作成功!'];
            } else {
                self::categorySelect();
                $coupon = Db::name('coupon')->select()->toArray();
                $this->assign('coupon', $coupon);
                return View::fetch('edit');
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    /**
     * 编辑商品
     * @author lijia
     * @date 2019-08-08
     */
    public function edit()
    {
        try {
            if (request()->isPost()) {
                $data = input('post.');
                if (!empty($data['images'])){
                    $data['images'] = json_encode($data['images'],true);
                }else{
                    return ['code' => 3000, 'msg' => '请添加商品轮播'];
                }
                unset($data['file']);
                $where['id'] = $data['id'];
                goodsModel::update($data, $where);
                return ['code' => 0, 'msg' => '操作成功!'];
            } else {
                $id = input('id', 0, 'intval');
                if (!$id) {
                    return ['code' => 1, 'msg' => '非法请求!'];
                }
                $info = Db::name('goods')->find($id);
                $coupon = Db::name('coupon')->select()->toArray();
                $this->assign('coupon', $coupon);
                $this->assign('info', $info);
                self::categorySelect();
                return View::fetch();
            }
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    public function doDelete()
    {
        try {
            $id = input('request.id');
            if (!$id) {
                return ['code' => 3000, 'msg' => '请选择要删除的数据!'];
            }
            $type = Db::name('goods')->where("id", $id)->value('type');
            if ($type == 2){
                return ['code' => 3000, 'msg' => '礼包不能删除!'];
            }
            $result = Db::name('goods')->where("id", $id)->delete();
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }


    public function doStatus()
    {
        try {
            $id = input('request.id');
            $status = input('request.status');
            if (!$id) {
                return ['code' => 3000, 'msg' => '操作失败!'];
            }
            $result = Db::name('goods')->where("id", $id)->update(['status' => $status]);
            if ($result) {
                return ['code' => 0, 'msg' => '操作成功!'];
            }
            return ['code' => 3000, 'msg' => '操作失败!'];
        } catch (\Exception $e) {
            return ['code' => 99999, 'msg' => $e->getMessage()];
        }
    }

    public function getImages() {
        $id = input('param.id');
        $images = Db::name('goods')->where('id',$id)->value('images');
        if (!empty($images)){
            $arr = json_decode($images);
            return json_encode($arr);
        }
        return [];
    }

}